const { getAllArticles, getArticleById } = require('../../utils/articles-data');

Page({
  data: {
    articleId: '',
    article: null,
    isCollected: false,
    comments: [],
    commentInput: '',
    showCommentInput: false
  },

  onLoad: function(options) {
    if (options.id) {
      // 支持数字和字符串类型的ID
      const articleId = options.id;
      this.setData({
        articleId: articleId
      });
      this.loadArticle(articleId);
      this.loadComments(articleId);
      this.checkCollectionStatus(articleId);
    }
  },

  onShow: function() {
    // 页面显示时重新检查关注状态
    if (this.data.articleId) {
      this.loadArticle(this.data.articleId);
      this.checkCollectionStatus(this.data.articleId);
    }
  },

  // 加载文章数据
  loadArticle: function(articleId) {
    const article = getArticleById(articleId);
    if (article) {
      // 检查关注状态
      const followedAuthors = wx.getStorageSync('followedAuthors') || [];
      const isFollowed = followedAuthors.some(author => author.id === article.author.id);
      
      const updatedArticle = {
        ...article,
        isFollowed: isFollowed
      };
      
      this.setData({
        article: updatedArticle
      });
    } else {
      wx.showToast({
        title: '文章不存在',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 加载评论数据
  loadComments: function(articleId) {
    // 从本地存储获取评论数据
    const allComments = wx.getStorageSync('articleComments') || {};
    const articleComments = allComments[String(articleId)] || [];
    
    // 如果没有评论，为预设文章添加一些模拟评论
    if (articleComments.length === 0 && (typeof articleId === 'number' || /^\d+$/.test(articleId))) {
      const mockComments = [
        {
          id: 1,
          articleId: articleId,
          author: {
            name: '学习者小王',
            avatar: '/images/avatar.png'
          },
          content: '很有用的分享，感谢作者！',
          publishTime: '1小时前',
          likeCount: 3,
          isLiked: false
        },
        {
          id: 2,
          articleId: articleId,
          author: {
            name: '英语爱好者',
            avatar: '/images/avatar.png'
          },
          content: '这些方法我试过，确实很有效果。推荐大家都试试！',
          publishTime: '2小时前',
          likeCount: 5,
          isLiked: false
        },
        {
          id: 3,
          articleId: articleId,
          author: {
            name: 'Emma学姐',
            avatar: '/images/avatar.png'
          },
          content: '作为过来人，我觉得最重要的还是坚持练习。这些技巧确实很实用，但需要大量的练习才能熟练掌握。',
          publishTime: '3小时前',
          likeCount: 8,
          isLiked: true
        }
      ];
      
      this.setData({
        comments: mockComments
      });
    } else {
      this.setData({
        comments: articleComments
      });
    }
  },

  // 检查收藏状态
  checkCollectionStatus: function(articleId) {
    const collectedArticles = wx.getStorageSync('collectedArticles') || [];
    const isCollected = collectedArticles.some(item => String(item.id) === String(articleId));
    this.setData({
      isCollected: isCollected
    });
  },

  // 切换收藏状态
  toggleCollection: function() {
    const { article, isCollected } = this.data;
    let collectedArticles = wx.getStorageSync('collectedArticles') || [];

    if (isCollected) {
      // 取消收藏
      collectedArticles = collectedArticles.filter(item => String(item.id) !== String(article.id));
      this.setData({
        isCollected: false
      });
      wx.showToast({
        title: '已取消收藏',
        icon: 'none'
      });
    } else {
      // 添加收藏
      const collectedArticle = {
        id: article.id,
        title: article.title,
        author: article.author.name,
        publishTime: article.publishTime,
        collectTime: this.formatTime(new Date())
      };
      collectedArticles.push(collectedArticle);
      this.setData({
        isCollected: true
      });
      wx.showToast({
        title: '收藏成功',
        icon: 'success'
      });
    }

    wx.setStorageSync('collectedArticles', collectedArticles);
    
    // 通知profile页面更新收藏统计
    this.notifyProfileUpdate();
  },

  // 点赞文章
  toggleLike: function() {
    const { article } = this.data;
    const newLikeStatus = !article.isLiked;
    const newLikeCount = article.isLiked ? article.likeCount - 1 : article.likeCount + 1;
    
    const updatedArticle = {
      ...article,
      isLiked: newLikeStatus,
      likeCount: newLikeCount
    };
    
    this.setData({
      article: updatedArticle
    });
    
    // 如果是用户发布的文章，同步更新用户发布文章列表
    this.updateUserPublishedArticleLike(article.id, newLikeCount);
    
    wx.showToast({
      title: updatedArticle.isLiked ? '点赞成功' : '已取消点赞',
      icon: 'success'
    });
  },

  // 更新用户发布文章的点赞数
  updateUserPublishedArticleLike: function(articleId, newLikeCount) {
    const userPublishedArticles = wx.getStorageSync('userPublishedArticles') || [];
    const updatedUserArticles = userPublishedArticles.map(article => {
      if (String(article.id) === String(articleId)) {
        return {
          ...article,
          likeCount: newLikeCount
        };
      }
      return article;
    });
    
    // 如果找到了匹配的文章，保存更新后的数据
    if (JSON.stringify(updatedUserArticles) !== JSON.stringify(userPublishedArticles)) {
      wx.setStorageSync('userPublishedArticles', updatedUserArticles);
      
      // 设置全局刷新标志
      const app = getApp();
      if (app.globalData) {
        app.globalData.needRefreshMyPublished = true;
      }
      
      // 通知my-published页面更新数据
      this.notifyMyPublishedUpdate();
      
      // 通知community页面更新数据  
      this.notifyCommunityUpdate(articleId, newLikeCount);
    }
  },

  // 更新用户发布文章的评论数
  updateUserPublishedArticleComment: function(articleId, newCommentCount) {
    const userPublishedArticles = wx.getStorageSync('userPublishedArticles') || [];
    const updatedUserArticles = userPublishedArticles.map(article => {
      if (String(article.id) === String(articleId)) {
        return {
          ...article,
          commentCount: newCommentCount
        };
      }
      return article;
    });
    
    // 如果找到了匹配的文章，保存更新后的数据
    if (JSON.stringify(updatedUserArticles) !== JSON.stringify(userPublishedArticles)) {
      wx.setStorageSync('userPublishedArticles', updatedUserArticles);
      
      // 设置全局刷新标志
      const app = getApp();
      if (app.globalData) {
        app.globalData.needRefreshMyPublished = true;
      }
      
      // 通知my-published页面更新数据
      this.notifyMyPublishedUpdate();
    }
  },

  // 通知my-published页面更新数据
  notifyMyPublishedUpdate: function() {
    const pages = getCurrentPages();
    const myPublishedPage = pages.find(page => page.route === 'pages/my-published/my-published');
    if (myPublishedPage && myPublishedPage.loadPublishedArticles) {
      myPublishedPage.loadPublishedArticles();
    }
  },

  // 通知community页面更新数据
  notifyCommunityUpdate: function(articleId, newLikeCount) {
    const pages = getCurrentPages();
    const communityPage = pages.find(page => page.route === 'pages/community/community');
    if (communityPage) {
      // 更新community页面的文章点赞数
      const updateCommunityArticles = (articles) => {
        return articles.map(article => {
          if (String(article.id) === String(articleId)) {
            return { ...article, likeCount: newLikeCount };
          }
          return article;
        });
      };

      if (communityPage.data.recommendArticles) {
        const updatedRecommendArticles = updateCommunityArticles(communityPage.data.recommendArticles);
        const updatedFollowArticles = updateCommunityArticles(communityPage.data.followArticles);
        const updatedCurrentArticles = updateCommunityArticles(communityPage.data.currentArticles);
        
        communityPage.setData({
          recommendArticles: updatedRecommendArticles,
          followArticles: updatedFollowArticles,
          currentArticles: updatedCurrentArticles
        });
      }
    }
  },

  // 关注/取消关注作者
  toggleFollow: function() {
    const { article } = this.data;
    const followedAuthors = wx.getStorageSync('followedAuthors') || [];
    
    const isCurrentlyFollowed = followedAuthors.some(author => author.id === article.author.id);
    
    let updatedFollowedAuthors;
    let message;
    
    if (isCurrentlyFollowed) {
      // 取消关注
      updatedFollowedAuthors = followedAuthors.filter(author => author.id !== article.author.id);
      message = '已取消关注';
    } else {
      // 添加关注
      updatedFollowedAuthors = [...followedAuthors, article.author];
      message = '关注成功';
    }
    
    // 保存到本地存储
    wx.setStorageSync('followedAuthors', updatedFollowedAuthors);
    
    // 更新文章的关注状态
    const updatedArticle = {
      ...article,
      isFollowed: !isCurrentlyFollowed
    };
    
    this.setData({
      article: updatedArticle
    });
    
    wx.showToast({
      title: message,
      icon: 'success'
    });
    
    // 通知其他页面更新用户统计数据
    this.notifyProfileUpdate();
  },

  // 显示评论输入框
  showCommentInput: function() {
    this.setData({
      showCommentInput: true
    });
  },

  // 隐藏评论输入框
  hideCommentInput: function() {
    this.setData({
      showCommentInput: false,
      commentInput: ''
    });
  },

  // 评论输入
  onCommentInput: function(e) {
    this.setData({
      commentInput: e.detail.value
    });
  },

  // 发布评论
  publishComment: function() {
    const { commentInput, comments, articleId, article } = this.data;
    
    if (!commentInput.trim()) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      });
      return;
    }

    // 创建新评论
    const newComment = {
      id: Date.now(),
      articleId: articleId,
      author: {
        name: '我', // 当前用户
        avatar: '/images/profile.png'
      },
      content: commentInput.trim(),
      publishTime: '刚刚',
      likeCount: 0
    };

    // 更新评论列表
    const updatedComments = [newComment, ...comments];
    
    // 更新文章评论数
    const newCommentCount = article.commentCount + 1;
    const updatedArticle = {
      ...article,
      commentCount: newCommentCount
    };

    this.setData({
      comments: updatedComments,
      article: updatedArticle,
      commentInput: '',
      showCommentInput: false
    });

    // 如果是用户发布的文章，同步更新评论数
    this.updateUserPublishedArticleComment(article.id, newCommentCount);

    // 保存评论到本地存储
    const allComments = wx.getStorageSync('articleComments') || {};
    if (!allComments[String(articleId)]) {
      allComments[String(articleId)] = [];
    }
    allComments[String(articleId)].push(newComment);
    wx.setStorageSync('articleComments', allComments);

    wx.showToast({
      title: '评论发布成功',
      icon: 'success'
    });
  },

  // 点赞评论
  likeComment: function(e) {
    const commentId = e.currentTarget.dataset.id;
    const updatedComments = this.data.comments.map(comment => {
      if (comment.id === commentId) {
        return {
          ...comment,
          isLiked: !comment.isLiked,
          likeCount: comment.isLiked ? comment.likeCount - 1 : comment.likeCount + 1
        };
      }
      return comment;
    });
    
    this.setData({
      comments: updatedComments
    });
  },

  // 分享文章
  shareArticle: function() {
    wx.showShareMenu({
      withShareTicket: true
    });
  },

  // 返回上一页
  goBack: function() {
    wx.navigateBack();
  },

  // 通知profile页面更新用户统计数据
  notifyProfileUpdate: function() {
    // 使用全局变量标记需要更新统计数据
    const app = getApp();
    if (app.globalData) {
      app.globalData.needUpdateStats = true;
    }
    
    // 或者直接获取当前页面栈中的profile页面并更新
    const pages = getCurrentPages();
    const profilePage = pages.find(page => page.route === 'pages/profile/profile');
    if (profilePage && profilePage.updateUserStats) {
      profilePage.updateUserStats();
    }
  },

  // 格式化时间
  formatTime: function(date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();

    return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
  }
}) 